<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>商品分类</title>
    <link rel="stylesheet" href="../layui/css/layui.css">
    <script src="../layui/layui.js"></script>

</head>
<body>
<div class="layui-container">
    <div class="layui-form-item">
        <div class="layui-input-inline">
            <input type="text" id="product-name-input" class="layui-input" placeholder="请输入商品名称">
        </div>
        <div class="layui-input-inline layui-col-md6">
            <select id="category-select" lay-filter="category">
                <option value="0">全部</option>
                <option th:each="category : ${categoryList}" th:value="${category.categoryId}" th:text="${category.categoryName}"></option>
            </select>
        </div>
        <div class="layui-input-inline">
            <button id="search-button" class="layui-btn layui-btn-radius">搜索</button>
        </div>
    </div>
</div>


<!--<div class="layui-container">-->
    <table class="layui-table">
        <colgroup>
            <col width="200">
            <col width="150">
            <col width="150">
            <col width="150">
            <!-- 其他商品属性列 -->
        </colgroup>
        <thead>
        <tr>
            <th>商品名称</th>
            <th>商品价格</th>
            <th>商品库存</th>
            <th>点击下单</th>
            <!-- 其他商品属性列 -->
        </tr>
        </thead>
        <tbody id="product-list">
        <!-- 使用Thymeleaf循环展示商品数据 -->
        <tr th:each="product : ${productlist}">
            <td th:text="${product.productName}"></td>
            <td th:text="${product.productPrice}"></td>
            <td th:text="${product.productLeft}"></td>
            <td>
                <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="placeOrder(this)">下单</button>
            </td>
        </tr>
        <!-- 如果商品列表为空，显示提示信息 -->
        <tr th:if="${#lists.isEmpty(productlist)}">
            <td colspan="3">暂无符合条件的商品</td>
        </tr>
        </tbody>
    </table>
<!--</div>-->

<script>

    function searchProduct() {
        var categoryId = document.getElementById('category-select').value;
        var productName = document.getElementById('product-name-input').value;

        // 发送 Ajax 请求，根据分类和商品名称查询商品数据
        // 注意根据实际情况调整请求的 URL 和参数名
        $.get('/kamun/product/getProductByCondition', {categoryId: categoryId, productName: productName}, function(data){
            // 将返回的整个页面代码作为字符串传入jQuery函数进行解析
            var parsedHtml = $(data);

            // 从解析后的HTML中提取商品数据
            var productListElement = parsedHtml.find('#product-list');
            var products = productListElement.find('tr').map(function() {
                var productRow = $(this);
                var productName = productRow.find('td:nth-child(1)').text();
                var productPrice = productRow.find('td:nth-child(2)').text();
                var productLeft = productRow.find('td:nth-child(3)').text();

                return {
                    productName: productName,
                    productPrice: productPrice,
                    productLeft: productLeft
                };
            }).get();

            // 在此处更新商品列表的数据内容
            var productListElement = $('#product-list');
            productListElement.empty(); // 清空商品列表的内容

            // 根据提取的商品数据重新生成商品列表的内容
            // 根据提取的商品数据重新生成商品列表的内容
            products.forEach(function(product) {
                var row = '<tr>' +
                    '<td>' + product.productName + '</td>' +
                    '<td>' + product.productPrice + '</td>' +
                    '<td>' + product.productLeft + '</td>' +
                    '<td>' +
                    '<button class="layui-btn layui-btn-sm layui-btn-normal" onclick="placeOrder(this)">下单</button>' +
                    '</td>' +
                    '</tr>';
                productListElement.append(row);
            });

            // 重新绑定下单按钮的点击事件
            productListElement.find('button').click(function() {
                placeOrder(this);
            });
        });
    }


    function placeOrder(button) {
        var row = $(button).closest('tr');
        var productName = row.find('td:nth-child(1)').text();
        var productPrice = row.find('td:nth-child(2)').text();
        var productLeft = row.find('td:nth-child(3)').text();

        layer.open({
            type: 1,
            title: '下单',
            content: '<div>订单状态：待支付</div>' +
                '<div>商品名称：' + productName + '</div>' +
                '<div>商品价格：' + productPrice + '</div>' +
                '<div>商品库存：' + productLeft + '</div>' +
                '<div>购买数量：<button class="layui-btn layui-btn-primary" onclick="decreaseQuantity()">-</button>' +
                '<span id="quantity">1</span>' +
                '<button class="layui-btn layui-btn-primary" onclick="increaseQuantity()">+</button></div>' +
                '<div>备注：<textarea id="shipping-address" class="layui-textarea" rows="4"></textarea></div>' +
                '<div>支付方式：<select id="payment-select" class="layui-select">' +
                '<option value="1">支付宝</option>' +
                '<option value="0">微信支付</option>' +
                '</select></div>',
            area: ['500px', '600px'],
            btn: ['确认下单','稍后支付', '取消'],
            yes: function(index, layero) {
                var quantity = parseInt($('#quantity').text());
                var shippingAddress = $('#shipping-address').val();
                var paymentMethod = $('#payment-select').val();

                var orderDetails = {
                    productName: productName,
                    productPrice: productPrice,
                    productQuantity: quantity,
                    orderTotal: parseFloat(productPrice) * quantity,
                    paymentMethod: paymentMethod,
                    shippingAddress: shippingAddress, // 根据实际需求添加其他字段
                };

                $.ajax({
                    url: '/kamun/order/insertOrder',
                    type: 'POST',
                    data: JSON.stringify(orderDetails),
                    contentType: 'application/json',
                    success: function(response) {
                        // if (response === 'success') {
                            layer.msg('下单成功');
                        // } else {
                        //     layer.msg('下单失败');
                        // }
                    },
                    error: function() {
                        layer.msg('请求失败，请重试');
                    },
                    complete: function() {
                        layer.close(index);
                    }
                });
            },
            btn2: function (index, layero) {
                var quantity = parseInt($('#quantity').text());
                var shippingAddress = $('#shipping-address').val();
                var paymentMethod = $('#payment-select').val();

                var orderDetails = {
                    productName: productName,
                    productPrice: productPrice,
                    productQuantity: quantity,
                    orderTotal: parseFloat(productPrice) * quantity,
                    paymentMethod: paymentMethod,
                    shippingAddress: shippingAddress
                };

                $.ajax({
                    url: '/kamun/order/pendingPayment',
                    type: 'POST',
                    data: JSON.stringify(orderDetails),
                    contentType: 'application/json',
                    success: function (response) {
                        layer.msg('订单已创建,未支付将在1小时内删除');
                    },
                    error: function () {
                        layer.msg('稍后支付请求失败');
                    },
                    complete: function () {
                        layer.close(index);
                    }
                });
                return false; // 阻止弹窗关闭
            },
            btn3: function(index, layero) {
                layer.close(index);
            }
        });
    }

    function decreaseQuantity() {
        var quantityElement = $('#quantity');
        var quantity = parseInt(quantityElement.text());
        if (quantity > 1) {
            quantity--;
            quantityElement.text(quantity);
        }
    }

    function increaseQuantity() {
        var quantityElement = $('#quantity');
        var quantity = parseInt(quantityElement.text());
        quantity++;
        quantityElement.text(quantity);
    }


    layui.use('form', function(){
        var form = layui.form;

        // 监听下拉框选择事件
        form.on('select(category)', function(data){
            searchProduct();
        });

        // 监听搜索按钮点击事件
        document.getElementById('search-button').addEventListener('click', function(){
            searchProduct();
        });
    });

</script>
</body>
</html>
